import json
from flask import Blueprint, app, jsonify, make_response,request
from flask_cors import cross_origin
from handle.logistics import *
from handle.providers import *
from handle.logger import logger

logistics_bp = Blueprint('logistics', __name__)

@logistics_bp.route('/providers', methods=['GET'])
def get_providers():
    logger.info("Get logistics providers list")
    data=get_providers_list()
    return json.dumps({"status": 200,"message": f"Create product","data": data},sort_keys=False)


@logistics_bp.route('/providers/', methods=['OPTIONS'])
@cross_origin()
def handle_options_request_1():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response

@logistics_bp.route('/providers/', methods=['POST'])
@cross_origin()
def create_provider():
    request_data=request.get_json()
    data=create_newprovider(request_data)
    logger.info("Create logistics provider")
    return json.dumps({"status": 200,"message": f"Create product","data": data},sort_keys=False)

@logistics_bp.route('/providers/<provider_id>', methods=['PUT'])
@cross_origin()
def update_provider(provider_id):
    request_data=request.get_json()
    request_data['VendorID']=provider_id
    data=update_provider_byid(request_data)
    logger.info("Update logistics provider")
    return json.dumps({"status": 200,"message": f"Update logistics provider","data": data},sort_keys=False)

@logistics_bp.route('/providers/<provider_id>', methods=['DELETE'])
@cross_origin()
def delete_provider(provider_id):
    del_provider_byid(provider_id)
    logger.info("Delete logistics provider")
    return json.dumps({"status": 200,"message": f"Delete logistics provider {provider_id}"},sort_keys=False)

@logistics_bp.route('/providers/dl', methods=['OPTIONS'])
@cross_origin()
def handle_options_request_8():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response

@logistics_bp.route('/providers/dl', methods=['DELETE'])
@cross_origin()
def delete_provider_dl():
    request_data=request.get_json()
    for provider_id in request_data:
        del_provider_byid(provider_id)
    logger.info("Delete logistics provider")
    return json.dumps({"status": 200,"message": f"Delete logistics provider {provider_id}"},sort_keys=False)







@logistics_bp.route('/orders', methods=['GET'])
def get_logistics_orders():
    data=get_logistics_list()
    return json.dumps({"status": 200,"message": f"Get logistics orders list","data": data})

@logistics_bp.route('/orders/csv', methods=['GET'])
def get_logistics_orders_csv():
    fieldnames = ["LogisticsID", "VendorID", "OrderID", "Address", "Consignee", "Telephone", "Status", "Remarks"]
    data=get_logistics_list()
    # 写入 CSV 文件到内存中
    csv_content = []
    csv_content.append(",".join(fieldnames))  # 写入表头
    for row in data:
        csv_content.append(",".join([str(row[field]) for field in fieldnames]))

    # 将 CSV 数据转换为字符串
    csv_data = "\r\n".join(csv_content).encode("gb18030")  # 使用 GB18030 编码

    # 构建响应
    response = make_response(csv_data)
    response.headers.set("Content-Disposition", "attachment", filename="logistics_orders.csv")
    response.headers.set("Content-Type", "text/csv; charset=gb18030")

    # 返回响应
    return response

@logistics_bp.route('/orders/csv', methods=['OPTIONS'])
@cross_origin()
def handle_options_request_4():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response


@logistics_bp.route('/orders/csv', methods=['POST'])
def get_logistics_orders_csv_ps():
    request_data=request.get_json()
    
    fieldnames = ["LogisticsID", "VendorID", "OrderID", "Address", "Consignee", "Telephone", "Status", "Remarks"]
    data=get_logistics_list()
    rt=[]
    for row in data:
        if request_data.get("IDList") != None:
            if row['LogisticsID'] not in request_data.get("IDList"):
                continue
        rt.append(row)
    # 写入 CSV 文件到内存中
    csv_content = []
    csv_content.append(",".join(fieldnames))  # 写入表头
    for row in rt:
        csv_content.append(",".join([str(row[field]) for field in fieldnames]))

    # 将 CSV 数据转换为字符串
    csv_data = "\r\n".join(csv_content).encode("gb18030")  # 使用 GB18030 编码

    # 构建响应
    response = make_response(csv_data)
    response.headers.set("Content-Disposition", "attachment", filename="logistics_orders.csv")
    response.headers.set("Content-Type", "text/csv; charset=gb18030")

    # 返回响应
    return response

@logistics_bp.route('/orders/', methods=['OPTIONS'])
@cross_origin()
def handle_options_request_2():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response

@logistics_bp.route('/orders', methods=['OPTIONS'])
@cross_origin()
def handle_options_request_3():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response





@logistics_bp.route('/orders/<LogisticsID>', methods=['PUT'])
def put_logistics_orders(LogisticsID):
    request_data=request.get_json()
    request_data['LogisticsID']=LogisticsID
    data=update_new_logistics(request_data)
    logger.info("Put logistics orders list")
    return json.dumps({"status": 200,"message": f"add logistics orders {LogisticsID}","data": data},sort_keys=False)




@logistics_bp.route('/orders/<logistics_order_id>', methods=['POST'])
def create_logistics_order(logistics_order_id):
    request_data=request.get_json()
    request_data['logistics_order_id']=logistics_order_id
    data=create_new_logistics(request_data)
    logger.info("Put logistics orders list")
    return json.dumps({"status": 200,"message": f"add logistics orders {logistics_order_id}","data": data},sort_keys=False)

@logistics_bp.route('/orders/dl', methods=['OPTIONS'])
@cross_origin()
def handle_options_request_7():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response

@logistics_bp.route('/orders/dl', methods=['DELETE'])
def delete_logistics_order_dl():
    request_data=request.get_json()
    logger.error(request_data)
    for logistics_order_id in request_data:
        del_logistics(logistics_order_id)
    logger.info("Delete logistics order")
    return json.dumps({"status": 200,"message": f"Delete logistics_order"},sort_keys=False)

@logistics_bp.route('/orders/<logistics_order_id>', methods=['DELETE'])
def delete_logistics_order(logistics_order_id):
    del_logistics(logistics_order_id)
    logger.info("Delete logistics order")
    return json.dumps({"status": 200,"message": f"Delete logistics_order {logistics_order_id}"},sort_keys=False)

@logistics_bp.route('/orders/<logistics_order_id>', methods=['GET'])
def get_logistics_order(logistics_order_id):
    data=get_logistics_byid(logistics_order_id)
    logger.info("Get logistics order")
    return json.dumps({"status": 200,"message": f"Get logistics_order_id {logistics_order_id}","data": data},sort_keys=False)

@logistics_bp.route('/orders/<logistics_order_id>/tracking', methods=['GET'])
def tracking_logistics_order(logistics_order_id):
    
    logger.info("Tracking logistics order")
    return jsonify({"message": f"tracking logistics_order_id {logistics_order_id}"})
